package com.we823.cms.common.json.model;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.we823.cms.common.json.JSONConstants;
import com.we823.cms.common.utils.RequestUtil;

public class JqgridModel<T> {
	public JqgridModel() {

	}

	public JqgridModel(HttpServletRequest request){
		page = RequestUtil.getValueByName(request, "page", 1);
		rows = RequestUtil.getValueByName(request, "rows", 10);
	}
	public JqgridModel(HttpServletRequest request,Model model){
		this(request);
		this.model = model;
	}
	/*
	public JqgridModel(HttpServletRequest request,List<T> datarows, Model model) {
		this(request);
		setDatarows(datarows);
		setModel(model);
		flush();
	}*/

	/**
	 * 当前所在页，默认为1
	 */
	private Integer page = 1;
	/**
	 * 总页数
	 */
	private Integer total = 1;
	/**
	 * 每页所含数据条数，默认为10
	 */
	private Integer rows = 10;
	/**
	 * 总记录条数
	 */
	private long records = 0;

	/**
	 * 返回给json的数据列表
	 */
	private List<T> datarows;

	/**
	 * 将所有数据包裹在model中，提给controller使用
	 */
	private Model model;

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public long getTotal() {
		if (records % rows == 0) {
			total = (int) (records / rows);
		} else {
			total = (int) (records / rows + 1);
		}
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public Integer getRows() {
		return rows;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	public long getRecords() {
		if (records == 0) {
			if (datarows != null) {
				records = datarows.size();
			} else {
				records = 0;
			}
		}
		return records;
	}

	public void setRecords(long records) {
		this.records = records;
	}

	public List<T> getDatarows() {
		return datarows;
	}

	public void setDatarows(List<T> datarows) {
		this.datarows = datarows;
	}

	public Model getModel() {
		flush();
		return model;
	}

	public void setModel(Model model) {
		if (model != null) {
			this.model = model;
		}
	}

	/**
	 * 提交数据
	 */
	public void flush(){
		if (model != null) {
			model.addAttribute(JSONConstants.PAGE, page);
			model.addAttribute(JSONConstants.ROWS, rows);
			model.addAttribute(JSONConstants.RECORDS, getRecords());
			model.addAttribute(JSONConstants.TOTAL, getTotal());
			model.addAttribute(JSONConstants.DATAROWS, datarows);
		}
	}
}
